//
//  STLoginViewController.swift
//  Story
//
//  Created by 汤泽川 on 2019/5/9.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import PKHUD

class STLoginViewController: UIViewController {

    enum STLoginState {
        case login
        case register
        case forget
        case change
        var titleStr : String {
            switch self {
            case .login:
                return "登陆"
            case .register:
                return "注册"
            case .forget:
                return "忘记密码"
            case .change:
                return "修改密码"
            }
        }
    }
    
    let closeBtn = UIButton()
    let disposeBag = DisposeBag()
    let stateObverser = BehaviorRelay<STLoginState>(value: .login)
    let sendEmailCountdown = BehaviorRelay<Int>(value: 0)
    
    let username = UITextField()
    let password = UITextField()
    let email = UITextField()
    let sendEmailBtn = UIButton()
    let verifyCode = UITextField()
    let conformBtn = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        buildView()
    }
    
    func buildView() {
        self.view.backgroundColor = .white
        closeBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: { [weak self] in
            self?.dismiss(animated: true, completion: nil)
        }).disposed(by: disposeBag)
        closeBtn.setImage(#imageLiteral(resourceName: "close_icon"), for: .normal)
        self.view.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(self.view.safeAreaInsets.top + 30)
            make.left.equalToSuperview().offset(18)
            make.size.equalTo(CGSize(width: 24, height: 24))
        }
        
        let titleLabel = UILabel()
        titleLabel.font = .boldSystemFont(ofSize: 31)
        titleLabel.textColor = .black
        titleLabel.text = "登陆"
        self.view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(closeBtn.snp_bottom).offset(40)
            make.left.equalToSuperview().offset(18)
            make.height.equalTo(40)
        }
        username.placeholder = "请输入用户名"
        username.font = .systemFont(ofSize: 24)
        username.textColor = .black
        username.keyboardType = .asciiCapable
        self.view.addSubview(username)
        username.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp_bottom).offset(18)
            make.left.right.equalToSuperview().inset(18)
            make.height.equalTo(40)
        }
        let usernameLine = UIView()
        usernameLine.backgroundColor = UIColor(white: 0, alpha: 0.1)
        self.view.addSubview(usernameLine)
        usernameLine.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(username)
            make.height.equalTo(1)
        }
        
        self.view.addSubview(password)
        let passwordHideBtn = UIButton()
        passwordHideBtn.setImage(#imageLiteral(resourceName: "password_show"), for: .normal)
        passwordHideBtn.setImage(#imageLiteral(resourceName: "password_hide"), for: .selected)
        passwordHideBtn.isSelected = true
        passwordHideBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            passwordHideBtn.isSelected = !passwordHideBtn.isSelected
            let str = self.password.text
            self.password.text = ""
            self.password.isSecureTextEntry = passwordHideBtn.isSelected
            self.password.text = str
        }).disposed(by: disposeBag)
        self.view.addSubview(passwordHideBtn)
        passwordHideBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(password)
            make.right.equalToSuperview().offset(-18)
            make.size.equalTo(CGSize(width: 30, height: 30))
        }
        
        password.placeholder = "请输入密码"
        password.isSecureTextEntry = true
        password.font = .systemFont(ofSize: 24)
        password.textColor = .black
        password.keyboardType = .asciiCapable
        password.snp.makeConstraints { (make) in
            make.top.equalTo(username.snp_bottom).offset(18)
            make.left.equalToSuperview().inset(18)
            make.height.equalTo(40)
            make.right.equalTo(passwordHideBtn.snp_left).offset(-5)
        }
        let passwordLine = UIView()
        passwordLine.backgroundColor = UIColor(white: 0, alpha: 0.1)
        self.view.addSubview(passwordLine)
        passwordLine.snp.makeConstraints { (make) in
            make.bottom.left.equalTo(password)
            make.height.equalTo(1)
            make.right.equalTo(passwordHideBtn)
        }
        
        self.view.addSubview(email)
        sendEmailBtn.setTitle("发送验证码", for: .normal)
        sendEmailBtn.titleLabel?.font = .systemFont(ofSize: 17)
        sendEmailBtn.setTitleColor(.gray, for: .normal)
        sendEmailBtn.layer.cornerRadius = 4
        sendEmailBtn.layer.borderWidth = 1
        sendEmailBtn.layer.borderColor = UIColor(white: 0, alpha: 0.1).cgColor
        sendEmailCountdown.delay(1, scheduler: MainScheduler.instance).subscribe(onNext: { (count) in
            if count == 0 {
                self.sendEmailBtn.setTitle("发送验证码", for: .normal)
                self.sendEmailBtn.isEnabled = true
            } else {
                self.sendEmailBtn.setTitle("\(count)s后重试", for: .normal)
                self.sendEmailBtn.isEnabled = false
                self.sendEmailCountdown.accept(self.sendEmailCountdown.value - 1)
            }
        }).disposed(by: disposeBag)
        sendEmailBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            if self.email.text != nil {
                HUD.show(.labeledProgress(title: nil, subtitle: "请稍后"))
                STEmailService().sendVerifyCode(toEmail: self.email.text!).result(callBack: { (error) in
                    HUD.hide()
                    if let error = error {
                        HUD.flash(.labeledError(title: nil, subtitle: error.localizedDescription))
                    } else {
                        self.sendEmailCountdown.accept(60)
                        HUD.flash(.success)
                    }
                })
            } else {
                HUD.flash(.labeledError(title: nil, subtitle: "邮箱不能为空"))
            }
        }).disposed(by: disposeBag)
        self.view.addSubview(sendEmailBtn)
        sendEmailBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(email)
            make.right.equalToSuperview().offset(-18)
            make.height.equalTo(email).offset(-4)
            make.width.equalTo(100)
        }
        
        email.placeholder = "请输入邮箱"
        email.font = .systemFont(ofSize: 24)
        email.textColor = .black
        email.keyboardType = .emailAddress
        email.snp.makeConstraints { (make) in
            make.top.equalTo(password.snp_bottom).offset(18)
            make.left.equalToSuperview().inset(18)
            make.height.equalTo(40)
            make.right.equalTo(sendEmailBtn.snp_left).offset(-5)
        }
        let emailLine = UIView()
        emailLine.backgroundColor = UIColor(white: 0, alpha: 0.1)
        email.addSubview(emailLine)
        emailLine.snp.makeConstraints { (make) in
            make.bottom.left.equalTo(email)
            make.height.equalTo(1)
            make.right.equalTo(sendEmailBtn)
        }
        
        verifyCode.placeholder = "请输入验证码"
        verifyCode.font = .systemFont(ofSize: 24)
        verifyCode.textColor = .black
        verifyCode.keyboardType = .asciiCapable
        self.view.addSubview(verifyCode)
        verifyCode.snp.makeConstraints { (make) in
            make.top.equalTo(email.snp_bottom).offset(18)
            make.left.right.equalToSuperview().inset(18)
            make.height.equalTo(40)
        }
        let verifyCodeLine = UIView()
        verifyCodeLine.backgroundColor = UIColor(white: 0, alpha: 0.1)
        verifyCode.addSubview(verifyCodeLine)
        verifyCodeLine.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(verifyCode)
            make.height.equalTo(1)
        }
        
        conformBtn.setTitle("确认", for: .normal)
        conformBtn.backgroundColor = .red
        conformBtn.titleLabel?.font = .boldSystemFont(ofSize: 21)
        conformBtn.addTarget(self, action: #selector(didClickConformBtn), for: .touchUpInside)
        self.view.addSubview(conformBtn)
        conformBtn.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(60 + self.view.safeAreaInsets.bottom)
        }
        
        let delegateBtn = UIButton()
        delegateBtn.setTitle("点击确定即代表您同意我们的《服务条款》", for: .normal)
        delegateBtn.setTitleColor(.blue, for: .normal)
        delegateBtn.titleLabel?.font = .systemFont(ofSize: 9)
        self.view.addSubview(delegateBtn)
        delegateBtn.snp.makeConstraints { (make) in
            make.bottom.equalTo(conformBtn.snp_top).offset(-8)
            make.centerX.equalToSuperview()
        }
        
        let forgetBtn = UIButton()
        forgetBtn.setTitle("找回密码", for: .normal)
        forgetBtn.setTitleColor(.blue, for: .normal)
        forgetBtn.titleLabel?.font = .systemFont(ofSize: 12)
        forgetBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            self.stateObverser.accept(.forget)
        }).disposed(by: disposeBag)
        self.view.addSubview(forgetBtn)
        forgetBtn.snp.makeConstraints { (make) in
            make.bottom.equalTo(delegateBtn.snp_top)
            make.right.equalTo(self.view.snp_centerX).offset(-5)
        }
        
        let registerBtn = UIButton()
        registerBtn.setTitle("注册账号", for: .normal)
        registerBtn.setTitleColor(.blue, for: .normal)
        registerBtn.titleLabel?.font = .systemFont(ofSize: 12)
        registerBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            self.stateObverser.accept(.register)
        }).disposed(by: disposeBag)
        self.view.addSubview(registerBtn)
        registerBtn.snp.makeConstraints { (make) in
            make.bottom.equalTo(delegateBtn.snp_top)
            make.left.equalTo(self.view.snp_centerX).offset(5)
        }
        
        let loginBtn = UIButton()
        loginBtn.setTitle("已有账号？立即登陆", for: .normal)
        loginBtn.setTitleColor(.blue, for: .normal)
        loginBtn.titleLabel?.font = .systemFont(ofSize: 12)
        loginBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            self.stateObverser.accept(.login)
        }).disposed(by: disposeBag)
        self.view.addSubview(loginBtn)
        loginBtn.snp.makeConstraints { (make) in
            make.bottom.equalTo(delegateBtn.snp_top)
            make.centerX.equalTo(self.view.snp_centerX)
        }
        
        stateObverser.subscribe(onNext: { (state) in
            self.password.placeholder = "请输入新密码"
            titleLabel.text = state.titleStr
            loginBtn.isHidden = false
            forgetBtn.isHidden = true
            registerBtn.isHidden = true
            if state == .login {
                self.password.placeholder = "请输入密码"
                self.email.isHidden = true
                self.verifyCode.isHidden = true
                self.sendEmailBtn.isHidden = true
                forgetBtn.isHidden = false
                registerBtn.isHidden = false
                loginBtn.isHidden = true
            } else {
                self.email.isHidden = false
                self.verifyCode.isHidden = false
                self.sendEmailBtn.isHidden = false
            }
            if state == .change {
                loginBtn.isHidden = true
            }
            
        }).disposed(by: disposeBag)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        username.resignFirstResponder()
        password.resignFirstResponder()
        email.resignFirstResponder()
        verifyCode.resignFirstResponder()
    }
    
    @objc func didClickConformBtn() {
        if self.username.text == "" || self.username.text == nil {
            HUD.flash(.labeledError(title: nil, subtitle: "用户名不能为空"))
        }
        if self.password.text == "" || self.password.text == nil {
            HUD.flash(.labeledError(title: nil, subtitle: "密码不能为空"))
        }
        if self.email.isHidden == false && (self.email.text == "" || self.email.text == nil) {
            HUD.flash(.labeledError(title: nil, subtitle: "邮箱不能为空"))
        }
        if self.verifyCode.isHidden == false && (self.verifyCode.text == "" || self.verifyCode.text == nil) {
            HUD.flash(.labeledError(title: nil, subtitle: "验证码不能为空"))
        }
        
        HUD.show(.progress)
        if self.stateObverser.value == .login {
            STUserService.shareInstance.login(username: self.username.text!, password: self.password.text!).result { (error) in
                HUD.hide()
                if error == nil {
                    HUD.flash(.success)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
                        self.dismiss(animated: true, completion: nil)
                    })
                } else {
                    HUD.flash(.labeledError(title: nil, subtitle: error?.localizedDescription))
                }
            }
        }
        if self.stateObverser.value == .change || self.stateObverser.value == .forget {
            STUserService.shareInstance.resetPassword(username: self.username.text!, password: self.password.text!, email: self.email.text!, verifyCode: self.verifyCode.text!).result { (error) in
                HUD.hide()
                if error == nil {
                    if self.stateObverser.value == .change {
                        HUD.flash(.labeledSuccess(title: nil, subtitle: "密码修改成功,请重新登录"))
                        STUserService.shareInstance.logout().result(callBack: { (error) in
                            if error == nil {
                                self.stateObverser.accept(.login)
                            } else {
                                HUD.flash(.labeledError(title: nil, subtitle: error?.localizedDescription))
                            }
                        })
                    } else {
                        HUD.flash(.success)
                        self.stateObverser.accept(.login)
                    }
                } else {
                    HUD.flash(.labeledError(title: nil, subtitle: error?.localizedDescription))
                }
            }
        }
        if self.stateObverser.value == .register {
            STUserService.shareInstance.register(username: self.username.text!, password: self.password.text!, email: self.email.text!, verifyCode: self.verifyCode.text!).result { (error) in
                HUD.hide()
                if error == nil {
                    HUD.flash(.success)
                    self.stateObverser.accept(.login)
                } else {
                    HUD.flash(.labeledError(title: nil, subtitle: error?.localizedDescription))
                }
            }
        }
    }
    
}
